package com.ruoyi.tb.lmt.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.tb.lmt.domain.bo.TbLmtrepairWorkdetailBo;
import com.ruoyi.tb.lmt.domain.bo.TbMessageNoticeBo;
import com.ruoyi.tb.lmt.domain.vo.TbLmtrepairWorkdetailVo;
import com.ruoyi.tb.lmt.domain.vo.TbMessageNoticeVo;
import com.ruoyi.tb.lmt.service.ITbLmtrepairWorkdetailService;
import com.ruoyi.tb.lmt.service.ITbMessageNoticeService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbLegacyIssuesVo;
import com.ruoyi.tb.lmt.domain.bo.TbLegacyIssuesBo;
import com.ruoyi.tb.lmt.service.ITbLegacyIssuesService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 遗留问题
 *
 * @author ruoyi
 * @date 2024-03-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/legacyIssues")
public class TbLegacyIssuesController extends BaseController {

    private final ITbLegacyIssuesService iTbLegacyIssuesService;

    private final ITbLmtrepairWorkdetailService iTbLmtrepairWorkdetailService;

    @Autowired
    private ITbMessageNoticeService iTbMessageNoticeService;

    @Autowired
    private ISysRoleService iSysRoleService;

    /**
     * 查询遗留问题列表
     */
    @GetMapping("/list")
    public TableDataInfo<TbLegacyIssuesVo> list(TbLegacyIssuesBo bo, PageQuery pageQuery) {
        return iTbLegacyIssuesService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出遗留问题列表
     */
    @Log(title = "遗留问题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbLegacyIssuesBo bo, HttpServletResponse response) {
        List<TbLegacyIssuesVo> list = iTbLegacyIssuesService.queryList(bo);
        ExcelUtil.exportExcel(list, "遗留问题", TbLegacyIssuesVo.class, response);
    }

    /**
     * 获取遗留问题详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<TbLegacyIssuesVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iTbLegacyIssuesService.queryById(id));
    }

    /**
     * 新增遗留问题
     */
    @Log(title = "遗留问题", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbLegacyIssuesBo bo) {
        return toAjax(iTbLegacyIssuesService.insertByBo(bo));
    }

    /**
     * 修改遗留问题
     */
    @Log(title = "遗留问题", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbLegacyIssuesBo bo) {
        return toAjax(iTbLegacyIssuesService.updateByBo(bo));
    }

    /**
     * 删除遗留问题
     *
     * @param ids 主键串
     */
    @Log(title = "遗留问题", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTbLegacyIssuesService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 查询遗留问题列表
     */
    @GetMapping("/selectList")
    public TableDataInfo<TbLegacyIssuesVo> selectList(String status, PageQuery pageQuery) {
        return iTbLegacyIssuesService.selectList(status, pageQuery);
    }


    /**
     * 查询遗留问题中的提料列表
     */
    @GetMapping("/selectExtractionList")
    public TableDataInfo<TbLegacyIssuesVo> selectExtractionList(String status, PageQuery pageQuery) {
        return iTbLegacyIssuesService.selectExtractionList(status, pageQuery);
    }

    /**
     * 遗留问题审批通过
     */
    @SaCheckPermission("xha-lmt:legacyIssues:pass")
    @Log(title = "遗留问题审批通过", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/pass")
    public R<?> pass(@Validated(EditGroup.class) @RequestBody TbLegacyIssuesBo bo) {

        String username = LoginHelper.getLoginUser().getUsername();
        if (!isUserInCaptain(username) && !isAdmin(username)) {
            throw new IllegalArgumentException("您没有权限审批该申请");
        }
        //更新任务明细表中遗留问题状态
        TbLmtrepairWorkdetailVo vo = iTbLmtrepairWorkdetailService.selectWorkInfo(bo.getWorkdetailId());
        TbLmtrepairWorkdetailBo boToUpdate = iTbLmtrepairWorkdetailService.selectWorkInfoBo(bo.getWorkdetailId());
        // 更新状态
        boToUpdate.setLegacyIssuesStatus(1);
        // 更新操作
        iTbLmtrepairWorkdetailService.updateByBo(boToUpdate);

        //更新遗留问题表状态
        bo.setLegacyIssuesStatus(1);
        bo.setStatus("已审批");
        iTbLegacyIssuesService.updateByBo(bo);
        return R.ok();
    }


    /**
     * 遗留问题提交完成
     */
    @SaCheckPermission("xha-lmt:legacyIssues:pass")
    @Log(title = "遗留问题审批提交完成", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/finish")
    public R<?> finish(@Validated(EditGroup.class) @RequestBody TbLegacyIssuesBo bo) {

        //更新任务明细表中遗留问题状态
        TbLmtrepairWorkdetailVo vo = iTbLmtrepairWorkdetailService.selectWorkInfo(bo.getWorkdetailId());
        TbLmtrepairWorkdetailBo boToUpdate = iTbLmtrepairWorkdetailService.selectWorkInfoBo(bo.getWorkdetailId());
        // 更新状态
        boToUpdate.setLegacyIssuesStatus(1);
        // 更新操作
        iTbLmtrepairWorkdetailService.updateByBo(boToUpdate);

        //更新遗留问题表状态
        bo.setLegacyIssuesStatus(1);
        bo.setStatus("已完成");
        iTbLegacyIssuesService.updateByBo(bo);
        return R.ok();
    }

    public boolean isAdmin(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有管理员角色
        for (SysRole role : userRoles) {
            if ("admin".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }

    public boolean isUserInCaptain(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有工队长的角色标识
        for (SysRole role : userRoles) {
            if ("captain".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 遗留问题审批不通过
     */
    @SaCheckPermission("xha-lmt:legacyIssues:refuseIssues")
    @Log(title = "遗留问题审批驳回", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/refuseIssues")
    public R<?> refuseIssues(@Validated(EditGroup.class) @RequestBody TbLegacyIssuesBo bo) {
        //添加到消息通知表中，
        //根据id查询通知表中原来的申请遗留信息
        TbMessageNoticeVo Message = null;
        try {
            Message = iTbMessageNoticeService.selectById(bo.getWorkdetailId());
        } catch (Exception e) {
            // 现在抛出一个新的RuntimeException
            throw new RuntimeException("已驳回");
        }
        //根据原来的申请遗留，新增通知消息
        TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
        TbLmtrepairWorkdetailVo list = iTbLmtrepairWorkdetailService.selectWorkInfo(bo.getWorkdetailId());
        messageNoticeBo.setMessageId(bo.getWorkdetailId());
        messageNoticeBo.setMessageTitle(list.getLmtNumber()+"任务申请遗留拒绝");
        messageNoticeBo.setMessageName(Message.getRecipient()+"拒绝了"+list.getLmtNumber()+"大机的任务遗留申请，请及时处理。");
        messageNoticeBo.setMessageType("遗留申请");
        messageNoticeBo.setLmtType(list.getLmtType());
        messageNoticeBo.setLmtNumber(list.getLmtNumber());
        messageNoticeBo.setWorkGroup(list.getWorkGroup());
        messageNoticeBo.setWorkUser(Message.getWorkUser());
        messageNoticeBo.setWorkerTeam(list.getWorkerTeam());
        messageNoticeBo.setStatus("0");
        messageNoticeBo.setWorkGroupId(Message.getWorkGroupId());
        messageNoticeBo.setTaskUrl(list.getTaskUrl());
        messageNoticeBo.setWorkTime(new Date());
        messageNoticeBo.setMessageNeed(Message.getWorkUser());
        iTbMessageNoticeService.insertByBo(messageNoticeBo);

        //更新任务明细表中内容
        TbLmtrepairWorkdetailBo boToUpdate = iTbLmtrepairWorkdetailService.selectWorkInfoBo(bo.getWorkdetailId());
        boToUpdate.setStatus("未派活");
        boToUpdate.setLegacyIssuesStatus(2);
        boToUpdate.setLegacyIssues("");
        boToUpdate.setLegacyIssuesData("");
        boToUpdate.setLegacyIssuesMaterial("");
        boToUpdate.setLegacyIssuesRemark("");
        boToUpdate.setLegacyIssuesSolution("");
        boToUpdate.setLegacyIssuesNumber("");
        iTbLmtrepairWorkdetailService.updateByBo(boToUpdate);

        bo.setStatus("被驳回");
        bo.setLegacyIssuesStatus(2);
        iTbLegacyIssuesService.updateByBo(bo);
        return R.ok();
    }

    /**
     * 获取遗留问题详细信息
     *
     * @param id 主键
     */
    @GetMapping("/select/{id}")
    public R<TbLegacyIssuesVo> getInfoById(@NotNull(message = "主键不能为空")
                                       @PathVariable Long id) {
        return R.ok(iTbLegacyIssuesService.selectById(id));
    }
}
